<script setup>
  import {projectApi} from "@/api/project.js";
  import {reactive, ref} from "vue";
  import { ElMessage ,ElMessageBox} from 'element-plus'
  import {
    Delete, Download,
    Edit, Upload,
  } from '@element-plus/icons-vue'
  import {contestApi} from "@/api/contest.js";
  import {facultyApi} from "@/api/faculty.js";
  import {researchersApi} from "@/api/researchers.js";
  const projectQuery = reactive({
    name:'',
    contest:'',
    page:1,
    size:10
  })
  //load data 加载表格数据
  const list = ref([])
  const total = ref(0)
  const loadData = ()=> {
    projectApi.list(projectQuery).then(result=>{
      console.log(projectQuery.page)
      if (result.code == 0){
        list.value = result.data
        total.value = result.count
      }
    })
  }
  loadData()

  //状态滑块
  const handleSwitchChange = (row) =>{
    console.log(row.approveId)
    projectApi.updateStatus(row).then(result=>{
      if (result.code==0){
        ElMessage.success("更新成功")
      }else {
        ElMessage.error("更新失败")
      }
    })
  }
  //搜索功能
  const onSubmit = () =>{
    projectApi.list(projectQuery).then(result=>{
      if (result.code == 0){
        list.value = result.data
        total.value = result.count
        projectQuery.page = 1
      }
    })
  }
  //loadData()
  //在页面加载时调用contestList()
  const contests = ref([])
  const contestList = () => {
    contestApi.list().then(result => {
      console.log(result.data)
      if (result.code == 0){
        contests.value = result.data
      }
    })
  }
  contestList()
  //单个删除
  const deleteDialog = ref(false)
  const currentId = ref()
  const deleteOneDialog = (id) =>{
    deleteDialog.value = true
    currentId.value = id
  }
  const deleteOne = (id) =>{
    projectApi.deleteOne(id).then(result=>{
      if (result.code==0){
        ElMessage.success("删除成功")
      }
      else {
        ElMessage.error("删除失败")
      }
      deleteDialog.value = false
      loadData()
    })
  }
  //批量删除
  //1.Define an "ids" to store the IDs of the variables to be deleted.
  const ids = ref([])
  const currentIds = ref([])
  const deleteAllDialog = ref(false)
  //2.把复选框中选中的id的值传递给ids.value
  function handSelectionChange(val){
    ids.value = val.map(item => item.id);
    console.log(ids.value)
  }
  //3.ok ids.value 已经有我想要的值了,现在把值传递给对话框吧
  const openDeleteAllDialog = () => {
    currentIds.value = ids.value;
    deleteAllDialog.value = true
  }
  //4.执行删除方法deleteAll
  const deleteAll = () => {
    projectApi.deleteAll(ids.value).then(result => {
      if (result.code == 0){
        ElMessage.success("delete success")
      }else {
        ElMessage.error("oops, something wrong")
      }
      deleteAllDialog.value = false;
      ids.value = []
      loadData()
    })
  }
  //审核
  const openExamDialog = ref(false)
  const showExam = (id) =>{
      openExamDialog.value = true
      projectVO.value = {}
    //赋值
    projectApi.getById(id).then(result => {

      projectVO.value = result.data
      console.log(result.data)
    })
  }
  //添加 or 编辑
  const openAddUpdateDialog = ref(false)
  const projectVO = ref({

  })
  //add
  const researchers = ref([])
  const researchersList = () => {
    researchersApi.list().then(result=>{
      if (result.code == 0){
        researchers.value = result.data
      }
    })
  }
  researchersList()
  const showAddDialog = () => {
    openAddUpdateDialog.value = true
    projectVO.value = {}

  }
  const showUpdateDialog = (id) => {
    openAddUpdateDialog.value = true;
    projectVO.value = {};
    projectApi.getById(id).then(result => {

        projectVO.value = result.data
        console.log(result.data)
    })
    //projectVO.value.displayResearchers = row.researchers; // 显示研究人员名字
  };
  const updateOrAdd = () =>{
    if (projectVO.value.id!==null && projectVO.value.id!=undefined){
    projectApi.update(projectVO.value).then(result=>{
      if (result.code == 0){
        ElMessage.success("更新成功")
        openAddUpdateDialog.value = false
        loadData()
      }else {
        ElMessage.error("oops, something wrong")
      }
    })
    }
      projectApi.add(projectVO.value).then(result => {
        if (result.code == 0){
          ElMessage.success("添加成功")
          openAddUpdateDialog.value = false
          loadData()
        }else {
          ElMessage.error("oops, something wrong")
        }
      })


  }


  //查询学院
  const facultys = ref([])
  const facultyList = () => {
    facultyApi.list().then(result => {
      if (result.code == 0){
        facultys.value = result.data
        console.log(facultys.value)
      }
    })
  }
  facultyList()

  //导入、导出excel
  const exportExcel = () => {
    projectApi.exportExcel().then((result) => {
      let blob = new Blob([result], { type: "application/xlsx" });
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = "项目列表.xlsx"; // 重命名文件
      link.click();
      URL.revokeObjectURL(url);
    });
  }
  import {useTokenStore} from "@/store/token.js";
  const tokenStore = useTokenStore()
  const headers = ref({
    //携带token传递到后端
    Authorization: tokenStore.token
  })
  const success = () =>{
    ElMessage.success("成功")
  }
</script>

<template>
  <el-card>
    <template #header>
      <el-button type="primary" @click="showAddDialog" plain >添加</el-button>
      <el-button type="primary" v-model="ids" @click="openDeleteAllDialog(ids.value)" plain>批量删除</el-button>
      <el-button type="primary" :icon="Download" @click="exportExcel">导出Excel</el-button>
      <el-upload
          class="inline-block"
          multiple=""
          method="post"
          action="/api/project/importExcel"
          style="display:inline-block;margin-left: 12px"
          accept=".xlsx,.xls"
          :show-file-list="false"
          :on-success="success"
          :headers="headers"
          name="file">
        <el-button type="primary" :icon="Upload">导入Excel</el-button>
      </el-upload>
    </template>
<!-- 搜索表单 -->
  <el-form :inline="true" :model="projectQuery" class="demo-form-inline">
    <el-form-item label="项目名称">
      <el-input v-model="projectQuery.name" placeholder="请输入项目名" clearable />
    </el-form-item>
    <el-form-item label="选择竞赛">
      <el-select
          v-model="projectQuery.contest"
          placeholder="请选择竞赛"
          clearable
      >
        <el-option
            v-for="contest in contests"
            :key="contest.id"
            :label="contest.name"
            :value="contest.id" />

      </el-select>
    </el-form-item>
    <el-form-item label="报名时间" style="margin-right: 10px;">
      <el-date-picker
          v-model="projectQuery.declarationDate"
          type="date"
          placeholder="请选择日期"
          clearabl
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">Query</el-button>
    </el-form-item>
  </el-form>
  <!--  表格-->
  <el-table :data="list" style="width: 100%" @selection-change="handSelectionChange">
    <el-table-column type="selection" width="40" />
    <el-table-column fixed prop="id" label="ID" width="120"/>
    <el-table-column prop="name" label="项目名称" width="160"/>
    <el-table-column prop="contest" label="所属竞赛" width="130"/>
    <el-table-column prop="researchers" label="申请人" width="100"/>
    <el-table-column prop="faculty" label="所属学院" width="100"/>
    <el-table-column prop="declareFunds" label="申请资金" width="100"/>
<!--    <el-table-column prop="approveId" label="状态" width="90px">
      <template #default="scope">
        <el-tooltip :content="'Switch value: ' + value" placement="top">
          <el-switch
              v-model="scope.row.approveId"
              style="&#45;&#45;el-switch-on-color: #13ce66; &#45;&#45;el-switch-off-color: #ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitchChange(scope.row)"
          />
        </el-tooltip>
      </template>
    </el-table-column>-->
    <el-table-column prop="approveId" label="状态" width="80px">
      <template #default="scope">
    <span>
      {{ scope.row.approveId === 1 ? '已通过' : '未通过' }}
    </span>
      </template>
    </el-table-column>
    <el-table-column prop="declarationDate" label="提交时间" width="200"/>
    <el-table-column fixed="right" label="Operations" min-width="80">
      <template #default="{row}">
        <el-button type="danger" size="small" @click="deleteOneDialog(row.id)">
          删除
        </el-button>
        <el-button type="primary" size="small" @click="showUpdateDialog(row.id)">
          编辑
        </el-button>
        <el-button type="primary" size="small" @click="showExam(row.id)">
          审核
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 20px">

    <el-pagination
        v-model:current-page="projectQuery.page"
        v-model:page-size="projectQuery.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes,  pager, jumper"
        :total="total"
        @current-change="loadData"
    />
  </div>

<!-- delete -->
  <el-dialog
      v-model="deleteDialog"
      title="Warning"
      width="500"
      align-center
  >
    <span>你确定要删除 ID 为 {{ ids.value }} 的记录吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteDialog = false">Cancel</el-button>
        <el-button type="primary" @click="deleteOne">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
<!-- 批量删除 -->
  <el-dialog
      v-model="deleteAllDialog"
      title="Warning"
      width="500"
      align-center
  >
    <span>你确定要删除 ID 为 {{ currentIds }} 的记录吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteAllDialog = false">Cancel</el-button>
        <el-button type="primary" @click="deleteAll(currentIds)">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
  </el-card>

<!-- 添加和编辑弹出框 -->
  <el-dialog v-model="openAddUpdateDialog" title="编写项目" width="500">
    <el-form :model="projectVO">
      <el-form-item label="项目名称" >
        <el-input v-model="projectVO.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="项目描述" >
        <el-input v-model="projectVO.content" autocomplete="off" />
      </el-form-item>
      <el-form-item label="竞赛名称" >
        <el-select
            v-model="projectVO.contestId"
            placeholder="pick contest"
            clearable
        >
          <el-option
              v-for="contest in contests"
              :key="contest.id"
              :label="contest.name"
              :value="contest.id" />

        </el-select>
      </el-form-item>

      <el-form-item label="申请人员" >
        <el-select
            v-model="projectVO.researchersId"
            placeholder="选择报名人员"
            clearable
        >
          <el-option
              v-for="researcher in researchers"
              :key="researcher.id"
              :label="researcher.name"
              :value="researcher.id" />

        </el-select>
      </el-form-item>

      <el-form-item label="所属学院" >
        <el-select
            v-model="projectVO.faculty"
            placeholder="pick contest"
            clearable
        >
          <el-option
              v-for="faculty in facultys"
              :key="faculty.id"
              :label="faculty.name"
              :value="faculty.id" />

        </el-select>
      </el-form-item>
      <el-form-item label="申请资金" >
        <el-input v-model="projectVO.declareFunds" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="openAddUpdateDialog = false">Cancel</el-button>
        <el-button type="primary" @click="updateOrAdd">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="openExamDialog" title="项目审核" width="500">
    <el-form-item label="项目审核">
      <el-select
          v-model="projectVO.approveId"
          placeholder="选择审核结果"
          clearable
      >
        <el-option
            :key="1"
            label="通过"
            :value="1" />
        <el-option
            :key="0"
            label="未通过"
            :value="0" />
      </el-select>
    </el-form-item>

    <el-form-item label="添加评价" >
      <el-input v-model="projectVO.commit" autocomplete="off" />
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="openAddUpdateDialog = false">Cancel</el-button>
        <el-button type="primary" @click="updateOrAdd">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>